from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
import csv
import time

class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def error(self, reqId, errorCode, errorString):
        print("Error: ", reqId, " ", errorCode, " ", errorString)

    # def contractDetails(self, reqId, contractDetails):
    #     print("contractDetails: ", reqId, " ", contractDetails)

    # def tickPrice(self, reqId, tickType, price, attrib):
    #     print("Tick Price. Ticker Id:", reqId, "tickType:", TickTypeEnum.to_str(tickType), "Price:", price, end=' ')

    # def tickSize(self, reqId, tickType, size):
    #     print("Tick Size. Ticker Id:", reqId, "tickType:", TickTypeEnum.to_str(tickType), "Size:", size)

    def mktDepthExchanges(self,depthMktDataDescriptions):
        global keeprun
        print("depthMktData:",depthMktDataDescriptions,len(depthMktDataDescriptions))
        # keeprun = True

    def historicalData(self, reqId, bar):
        print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open, "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume, "Count:", bar.barCount, "WAP:", bar.average)

    def historicalTicksBidAsk(self,reqId,ticks,done):
        print("HistoricalTicksBidAsk:",reqId,"ticks:",ticks,"done:",done)

    def dailyStockDate(self,index,symbol):
        print(index,"run")
        contract = Contract()
        contract.symbol = symbol
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
        contract.primaryExchange = "NASDAQ"
        app.reqMktData(1, contract, "233", False, False, [])
        app.reqMktDepthExchanges()


def main():
    global app
    global keeprun
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)
    app.reqMarketDataType(4) # 4为延时数据，我的未认证账户测试用，认证账户注释掉
    with open('./files/nasdaq.csv','r') as f:
        reader = csv.reader(f)
        # keeprun = True
        # while keeprun:
        stockList = []
        for index,item in enumerate(reader):
            try:
                turnover = round(((float(item[8])/(float(item[5])/float(item[2][1:])))*100),2)
                stockList.append([item[0],turnover])
            except:
                pass
        def takeTurnover(elem):
            return elem[1]
        stockList.sort(key=takeTurnover,reverse=True)
        needStockList = stockList[0:5]
        for index,item in enumerate(needStockList):
            print(index,item[0],item[1])
            app.dailyStockDate(index,item[0])
            # keeprun = False
            # time.sleep(1)

    # app.reqContractDetails(1, contract)
    # app.reqMarketDataType(4)
    # app.reqMktData(1, contract, "233", False, False, [])
    # app.reqMktDepthExchanges()
    # app.reqHistoricalData(1, contract, "", "1 D", "1 min", "BID_ASK", 0, 1, False, [])
    # app.reqHistoricalTicks(1,contract,"","20210115 12:01:00",10,"Bid_Ask",0,True,[])

    app.run()


if __name__ == "__main__":
    main()